#!/usr/bin/env python

################################################################################
#IMPORTS
import os
import urllib

import webapp2
import jinja2
import webapp2

from google.appengine.api import users
from google.appengine.ext import ndb


################################################################################
#CONSTANT VARIABLES
JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

################################################################################
#CLASSES
class Project(ndb.Model):
    """A main model for representing Project entry."""
    
    """name refers to the name of the Project"""
    name = ndb.StringProperty(required = True, indexed=True)
    
    """entry_date refers to the date that this record was added"""
    entry_date = ndb.DateTimeProperty(auto_now_add=True)
    
    """modified_date refers to the date that this record was modified"""
    modified_date = ndb.DateTimeProperty(auto_now_add=True)


class MainHandler(webapp2.RequestHandler):
    def get(self):
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('html/index.html')
        self.response.write(template.render(template_values))

class ProjectController(object):
    def get_record_list(self):
        project_query = Project.query().order(-Project.name)
        project_records = project_query.fetch(10)
        return project_records
    
    def get(self, urlsafe_key):
        project = None
        if len(urlsafe_key) > 0:
            try:
                key = ndb.Key(urlsafe=urlsafe_key)
                project = key.get()
            except:
                project = None
        return project
    
    def add(self, project_name):
        result = False
        try:
            project = Project()
            project.name = project_name
            #TODO: Should rightfully check to make sure that the name that we selected are not repeated before inserting.
            project.put()
            result = True
        except:
            result = False
        return result
            
        
    def delete(self, urlsafe_key):
        result = False
        if len(urlsafe_key) > 0:
            try:
                key = ndb.Key(urlsafe=urlsafe_key)
                project = key.get()
                project.key.delete()
                result = True
            except:
                result = False
        return result
    
    def update(self, urlsafe_key, project_name):
        result = False
        if len(urlsafe_key) > 0:
            try:
                key = ndb.Key(urlsafe=urlsafe_key)
                project = key.get()
                project.name = project_name
                project.put()
                result = True
            except:
                result = False
        return result

class ListProjectHandler(webapp2.RequestHandler):
    def get(self):
        controller = ProjectController()
        template_values = {}
        template_values['project_records'] = controller.get_record_list()
        template = JINJA_ENVIRONMENT.get_template('html/list-project-react.html')
        self.response.write(template.render(template_values))
        
class AddProjectHandler(webapp2.RequestHandler):
    def get(self):
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('html/add-project.html')
        self.response.write(template.render(template_values))
        
    def post(self):
        controller = ProjectController()
        controller.add(self.request.get('project_name'))
        template_values = {}
        template_values["message"] = "all done"
        template = JINJA_ENVIRONMENT.get_template('html/add-project.html')
        self.response.write(template.render(template_values))
        
class DeleteProjectHandler(webapp2.RequestHandler):
    def get(self):
        urlsafe_key = self.request.get("key")
        controller = ProjectController()
        template_values = {}
        template_values['project'] = controller.get(urlsafe_key)
        template = JINJA_ENVIRONMENT.get_template('html/delete-project.html')
        self.response.write(template.render(template_values))
        
    def post(self):
        urlsafe_key = self.request.get("key")
        controller = ProjectController()
        controller.delete(urlsafe_key)
        template_values = {}
        template_values["message"] = "all done"
        template = JINJA_ENVIRONMENT.get_template('html/add-project.html')
        self.response.write(template.render(template_values))
        
class EditProjectHandler(webapp2.RequestHandler):
    def get(self):
        urlsafe_key = self.request.get("key")
        controller = ProjectController()
        template_values = {}
        template_values['project'] = controller.get(urlsafe_key)
        template = JINJA_ENVIRONMENT.get_template('html/edit-project.html')
        self.response.write(template.render(template_values))
        
    def post(self):
        urlsafe_key = self.request.get("key")
        controller = ProjectController()
        controller.update(urlsafe_key,
                          self.request.get('project_name'))
        template_values = {}
        template_values['project'] = controller.get(urlsafe_key)
        template_values["message"] = "all done"
        template = JINJA_ENVIRONMENT.get_template('html/edit-project.html')
        self.response.write(template.render(template_values))
        
class ViewProjectHandler(webapp2.RequestHandler):
    def get(self):
        urlsafe_key = self.request.get("key")
        controller = ProjectController()
        template_values = {}
        template_values['project'] = controller.get(urlsafe_key)
        template = JINJA_ENVIRONMENT.get_template('html/view-project.html')
        self.response.write(template.render(template_values))
        

app = webapp2.WSGIApplication([
    (r'/', MainHandler),
    (r'(?i)/projects', ListProjectHandler),
    (r'(?i)/list-project', ListProjectHandler),
    (r'(?i)/add-project', AddProjectHandler),
    (r'(?i)/delete-project', DeleteProjectHandler),
    (r'(?i)/edit-project', EditProjectHandler),
    (r'(?i)/view-project', ViewProjectHandler)
], debug=True)
